package pannel.category;

import utils.JDBCUtils;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CategoryDao {
    private static final String TABLE_NAME = "category";

    // 新增分类
    public boolean insert(Category category) throws SQLException {
        String sql = "INSERT INTO " + TABLE_NAME + " (name, description) VALUES (?, ?)";
        int affected = (int) JDBCUtils.execute(sql,
                category.getName(),
                category.getDescription()
        );
        return affected > 0;
    }

    // 根据ID更新分类
    public boolean updateById(Category category) throws SQLException {
        String sql = "UPDATE " + TABLE_NAME + " SET name = ?, description = ? WHERE id = ?";
        int affected = (int) JDBCUtils.execute(sql,
                category.getName(),
                category.getDescription(),
                category.getId()
        );
        return affected > 0;
    }

    // 根据ID删除分类
    public boolean deleteById(Integer id) throws SQLException {
        String sql = "DELETE FROM " + TABLE_NAME + " WHERE id = ?";
        int affected = (int) JDBCUtils.execute(sql, id);
        return affected > 0;
    }

    // 分页模糊查询
    public List<Category> pageQuery(String name, Integer pageNum, Integer pageSize) throws SQLException {
        String sql = "SELECT * FROM " + TABLE_NAME + " WHERE name LIKE ? LIMIT ?, ?";
        ResultSet rs = (ResultSet) JDBCUtils.execute(sql,
                "%" + (name != null ? name : "") + "%",
                (pageNum - 1) * pageSize,
                pageSize
        );

        List<Category> categories = new ArrayList<>();
        while (rs.next()) {
            categories.add(mapResultSetToCategory(rs));
        }
        return categories;
    }

    // 获取总记录数
    public int getTotalCount(String name) throws SQLException {
        String sql = "SELECT COUNT(*) as total FROM " + TABLE_NAME + " WHERE name LIKE ?";
        ResultSet rs = (ResultSet) JDBCUtils.execute(sql,
                "%" + (name != null ? name : "") + "%"
        );
        return rs.next() ? rs.getInt("total") : 0;
    }

    // ResultSet 映射到 Category 对象
    private Category mapResultSetToCategory(ResultSet rs) throws SQLException {
        return Category.builder()
                .id(rs.getInt("id"))
                .name(rs.getString("name"))
                .description(rs.getString("description"))
                .build();
    }

    // 获取所有分类
    public List<Category> findAll() throws SQLException {
        String sql = "SELECT * FROM " + TABLE_NAME;
        ResultSet rs = (ResultSet) JDBCUtils.execute(sql);
        
        List<Category> categories = new ArrayList<>();
        while (rs.next()) {
            categories.add(mapResultSetToCategory(rs));
        }
        return categories;
    }
} 